package com.user.profile.utils;

import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContextUtil implements ApplicationContextAware {

  private static ApplicationContext applicationContext;

  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.applicationContext = applicationContext;
  }


  public static Object getBean(String name) {
    try {
      return applicationContext.getBean(name);
    } catch (NoSuchBeanDefinitionException e) {
      return null;
    }
  }

  public static <T> T getBean(Class<T> clazz) {
    try {
      return applicationContext.getBean(clazz);
    } catch (NoSuchBeanDefinitionException e) {
      return null;
    }
  }

  public static <T> T getBean(String name, Class<T> clazz) {
    try {
      return applicationContext.getBean(name, clazz);
    } catch (NoSuchBeanDefinitionException e) {
      return null;
    }
  }

  public static <T> List<T> getBeans(Class<T> beanClass) {
    try {
      return new ArrayList(applicationContext.getBeansOfType(beanClass).values());
    } catch (NoSuchBeanDefinitionException e) {
      return null;
    }
  }
}
